package com.health.circle.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.health.circle.R;
import com.health.circle.base.BaseActivity;
import com.health.circle.utils.HttpUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

public class RegisterActivity extends BaseActivity implements OnClickListener {

	private Button mBtnBack;

	private Button mBtnRegister;

	private TextView mTvLoginName;

	private TextView mTvLoginPwd;

	private static final int REGISTER_SUCCESS = 0;

	private static final int REGISTER_FAIL = 1;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REGISTER_SUCCESS:
				registerSuccess();
				break;

			case REGISTER_FAIL:
				registerFail();
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		initView();
	}

	private void initView() {

		mBtnBack = (Button) findViewById(R.id.btn_back);
		mBtnBack.setOnClickListener(this);

		mBtnRegister = (Button) findViewById(R.id.btn_register);
		mBtnRegister.setOnClickListener(this);

		mTvLoginName = (TextView) findViewById(R.id.edit_login_name);
		mTvLoginPwd = (TextView) findViewById(R.id.edit_login_pwd);
	}

	private void registerSuccess() {
		
		progressHide();
		
		Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
		this.finish();
		
	}

	private void registerFail() {
		progressHide();
		
		Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
	}

	private void register() {
		
		progressShow("注册中，请稍等！");

		String loginName = mTvLoginName.getText().toString();
		String loginPwd = mTvLoginPwd.getText().toString();

		String url = HttpUtil.BASE_URL;

		AsyncHttpClient client = HttpUtil.getAsyncHttpClient();
		client.get(url, new JsonHttpResponseHandler() {

			@Override
			public void onFailure(Throwable e, JSONObject errorResponse) {
				Message msg = Message.obtain(mHandler, REGISTER_FAIL);
				mHandler.sendMessage(msg);
			}

			@Override
			public void onSuccess(JSONObject response) {
				Message msg = Message.obtain(mHandler, REGISTER_SUCCESS);
				// msg.getData().putInt("responsecode", responseCode);
				mHandler.sendMessage(msg);
			}

		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			super.finish();
			break;
		case R.id.btn_register:
			register();
			break;

		default:
			break;
		}
	}

}
